//@flow

import { 
    Toast,
 } from "antd-mobile-rn";
import CodePush,{RemotePackage,LocalPackage,DownloadProgress} from "react-native-code-push";
import { SETUP_CHECKING, UPDATE_STATUS, UPDATE_PROGRESS, UPDATE_META_INFO, UPDATE_PACKAGE_INFO, UPDATE_CODE_PUSH_PACKAGE } from "./version.type";
import { VersionState, UpdateStatus, LastestVersionSource } from "./version.state";
import { ResponseBaseModal } from "../../service/modal/baseModal/responseBaseModal";
import { AppVersionInfoModal } from "../../service/modal/responseModal/appVersionInfoModal";
import * as api from "../../service/api";
import { ResponseResultStatus } from "../../service/business/ResponseResultStatus";
import { companyBinaryVersion } from "../../util/common";
import * as Config from "../../config/config";


/**初始化获取本地版本 */
export function setupMetaVersion(){
    return async  dispatch=>{
        dispatch(updateMetaInfo('','正在获取版本信息'))
        let {BUNDLE_VERSION,BINDRARY_VERSION} = await getMetaInfo();
        dispatch(updateMetaInfo(BUNDLE_VERSION,BINDRARY_VERSION));
    }

}

export  function setupChecking(){
    try {
        return async dispatch=>{
            console.log('开始之心')
            dispatch(updateStatus(UpdateStatus.CheckingAppStoreUpdate,'正在检查更新'))
            return api.queryAppStoreInfo().then(res=>{
                let modal:AppVersionInfoModal ;
                if(res.code == ResponseResultStatus.Success){
                    modal = new AppVersionInfoModal(res.data);
                    //获取到服务端版本成功
                    console.log(`获取app store版本成功，即将进行本地匹配`);
                    let hasUpdate:boolean = companyBinaryVersion(Config.BINDRARY_VERSION,modal.version);
                    if(hasUpdate){
                        dispatch(updateStatus(UpdateStatus.AppStoreHasUpdate,'发现新版本'));
                        //修改更新包的更新信息
                        dispatch(updateLastestPackageInfo(modal.version,null,modal.packageSize,modal.desc,false,LastestVersionSource.FROM_APP_STORE))
                    }else{
                        dispatch(updateStatus(UpdateStatus.CheckingCodePushUpdate,'检查热更新'));
                        //没有app store版本，不一定是真的没有，可能手动维护数据出错导致的，直接判断热更新版本
                        codePushChecking(dispatch);
                    }
                }else{
                    //获取store版本失败，依然检查热更新版本
                    codePushChecking(dispatch);
                }
            });
            
        }
    } catch (error) {
        throw new Error('检查app更新出现异常:\n'+JSON.stringify(error))
        dispatch(updateStatus(UpdateStatus.CheckingAppStoreUpdate,'正在检查商店更新'))
    }
    
}
/**更新 更新包 的相关信息 */
export function updateLastestPackageInfo(latestAppVersion:string,latestCodePushLabel:string,lastestSize:number,lastestDes:string,isMandatory:boolean,fromSource:LastestVersionSource,remotePackage?:RemotePackage=null){
    return {
        type : UPDATE_PACKAGE_INFO,
        latestAppVersion,
        latestCodePushLabel,
        lastestSize,
        lastestDes,
        isMandatory,
        fromSource,
        remotePackage
    }
}
/**检查code push更新 */
async function codePushChecking(dispatch){
    let rPackage:RemotePackage = await CodePush.checkForUpdate();
    if(rPackage){
        //发现有code push 版本
        dispatch(updateStatus(UpdateStatus.CodePushHasUpdate,'发现新版本'))
        dispatch(updateLastestPackageInfo(rPackage.appVersion,rPackage.label,rPackage.packageSize,rPackage.description,rPackage.isMandatory,LastestVersionSource.FROM_CODE_PUSH,rPackage))
    }else{
        //没有发现有热更新包,
        dispatch(updateStatus(UpdateStatus.CodePushNotUpdate,'没有发现更新'))
    }
}

export function onDownloadClick(rPackage:RemotePackage){
    return async dispatch=>{
                //开始下载bundle包
            dispatch(updateStatus(UpdateStatus.CodePushDownloadingUpdate,'正在下载更新包'));
            let lPackage :LocalPackage = await rPackage.download((progress)=>{
                console.log(`下载进度:${progress.receivedBytes}`)
                dispatch(updateDownloadProgress(progress));
                //监听下载进度变化
            });
            //下载完成
            dispatch(updateStatus(UpdateStatus.CodePushDownloadedUpdate,'下载完成，即将安装'));
            if(lPackage){
                //开始安装
                dispatch(updateStatus(UpdateStatus.CodePushInstalling,'正在安装'))
                lPackage.install(CodePush.InstallMode.IMMEDIATE).then(installRes=>{
                    //安装完成,即将重启
                    dispatch(updateStatus(UpdateStatus.CodePushInstalled,'安装完成，即将重启'))
                    CodePush.allowRestart()
                    //短暂提示，app即将重启
                    setTimeout(()=>{
                        CodePush.restartApp()
                    },2000)
                    
    
                })
            }
    }
}

export function updateStatus(newStatus:UpdateStatus,tipLabel:string){
    return {
        type : UPDATE_STATUS,
        updateState:newStatus,
        tipLabel,
    }
}
export function updateCodePushPackage(rPackage:RemotePackage){
    return {
        type : UPDATE_CODE_PUSH_PACKAGE,
        remotePackage:rPackage,
    }
}

export function updateDownloadProgress(newProgress:DownloadProgress){
    return {
        type:UPDATE_PROGRESS,
        downloadProgress:(newProgress.receivedBytes / newProgress.totalBytes)*100
    }
}
/**
 * 
 * @param {js包版本} BUNDLE_VERSION 
 * @param {二进制文件版本} BINDRARY_VERSION 
 */
export function updateMetaInfo(BUNDLE_VERSION:string,BINDRARY_VERSION:string){
    return {
        type:UPDATE_META_INFO,
        metaAppVersion:BINDRARY_VERSION,
        metaLabel:BUNDLE_VERSION,
    }
}

/**获取本地版本信息 */
export async function getMetaInfo():Promise<{BINDRARY_VERSION:string,BUNDLE_VERSION:string}>{
    let lPackage:LocalPackage=await CodePush.getUpdateMetadata();
    if(lPackage){
        return {
            BINDRARY_VERSION : lPackage.appVersion,
            BUNDLE_VERSION	 : lPackage.label.replace('v')
        }
    }else{
        return Promise.resolve({
            BINDRARY_VERSION	:Config.BINDRARY_VERSION,
            BUNDLE_VERSION	    :Config.BUNDLE_VERSION
        })
    }
}